#include "pere.h"


static void init_surv ( fd_set *s , int desc_num )
{
	FD_ZERO (s);
	FD_SET (desc_num ,s);
	return ;
}


int m ( int argc , char * argv []) {
	fd_set readt ;
	int retval ;
	char retbuf [ MAXSIZE ];
	char desc_string [ MAXSIZE ];
	int tuyaux [2];
	FILE * the_stream ;

	if ( pipe ( tuyaux )== -1) {
		fprintf ( stderr ," Impossible de tuyauter\n");
		exit ( EXIT_FAILURE );
	}

	switch ( fork ()) {
		case -1: /* Erreur */
			fprintf ( stderr ," Impossible de forker\n");
			exit ( EXIT_FAILURE );
			break ;
		default : /* pere */
			close ( tuyaux [1]);
			sleep (2);
			break ;
		case 0: /* fils */
			close ( tuyaux [0]);
			sprintf ( desc_string , "%d" , tuyaux [1]);
			execlp ( XTERM , XTERM ,"-e" ,"./writer" , desc_string , NULL );
			fprintf ( stderr ," Impossible de recouvrir\n");
			exit ( EXIT_FAILURE );
			break ;
	}
	if (( the_stream = fdopen ( tuyaux [0] ,"r")) == NULL ) {
		fprintf ( stderr ," Impossible d'ouvrir le desc !\n");
		exit ( EXIT_FAILURE );
	}

	init_surv (& readt , tuyaux [0]);
	while (1) {
		select ( tuyaux [0]+1 , & readt , NULL , NULL , NULL );
		if ( FD_ISSET ( tuyaux [0] , & readt )) {
			retval = read_and_parse ( the_stream , retbuf );
			if ( retval < 0) {
				exit ( EXIT_FAILURE );
			}
			fprintf ( stdout ," Lu :\"%s\"\n" , retbuf );
		}

		init_surv(&readt , tuyaux[0]);
	}
}
